<?php
// +----------------------------------------------------------------------
// | 小牛Admin
// +----------------------------------------------------------------------
// | Website: www.xnadmin.cn
// +----------------------------------------------------------------------
// | Author: dav <85168163@qq.com>
// +----------------------------------------------------------------------

namespace app\admin\controller\curd\service;

use think\helper\Str;

class BuildModelFunction
{
    public function build($data)
    {
        $func = '';
        foreach ($data as $_data) {
            if ( $_data['column'] == 1 && in_array($_data['form_type'], ['radio', 'checkbox', 'select', 'switch'])) {
                $func .= $this->createFunction($_data).PHP_EOL.PHP_EOL;
            }
        }
        $func = str_replace('###', '$', $func);
        return $func;
    }

    protected function createFunction($data)
    {
        $rule = $data['form_rule'];
        if ( empty($rule) ) {
            retError('单选规则不能为空');
        }
        //$rule = explode(PHP_EOL, $rule);
        $rule = explode("\n", $rule);
        $_html = ''; // 单选html
        foreach ($rule as $k => $v) {
            $rule[$k] = trim($v);
            if ( empty($rule[$k]) ) {
                retError('单选规则不能为空');
            }
            $rule[$k] = explode('|', $rule[$k]);
            if ( count($rule[$k]) != 2 ) {
                retError('单选规则格式错误');
            }
            $_html .= <<<php
            '{$rule[$k][0]}' => '{$rule[$k][1]}',
php;
            $_html .= PHP_EOL;
        }
        $_html = trim($_html, PHP_EOL);

        $_field = str::studly($data['field']); //首字符大写的驼峰
        $function=<<<php
    public function get{$_field}Attr(###value,###data)
    {
        ###arr = [
{$_html}
        ];
        return ###arr[###data['{$data['field']}']];
    }
php;
        return $function;
    }
}
